package com.gofaraway.common.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;

import java.util.HashMap;
import java.util.Map;

/**
 * 占位符解析工具类
 *
 * @author ChenPeng
 * @Date 2024/7/24 16:27
 */
public class PlaceholderUtil {
    private static final String DEFAULT_VALUE_SPLIT = ":";

    private PlaceholderUtil() {
        throw new UnsupportedOperationException("工具类不允许实例化");
    }

    /**
     * 按照placeholders数组的下标位置替换对应的占位符，下标从0开始，且支持默认值，
     * 如："${0:参数}校验失败${2}"
     */
    public static String parse(String message, Object[] placeholders) {
        Map<String, String> placeHolderParams = new HashMap<>(4);
        if (ArrayUtils.isNotEmpty(placeholders)) {
            for (int i = 0; i < placeholders.length; i++) {
                placeHolderParams.put(String.valueOf(i), placeholders[i] == null ? StringUtils.EMPTY : placeholders[i].toString());
            }
        }
        return parse(message, placeHolderParams);
    }


    /**
     * 按位替换占位符，支持默认值；使用的方式参考：{@link StringSubstitutor}
     *
     * @param message 格式 ${占位符:默认值}
     */
    public static String parse(String message, Map<String, String> placeholders) {
        if (placeholders == null) {
            placeholders = new HashMap<>();
        }
        StringSubstitutor sub = new StringSubstitutor(placeholders);
        sub.setValueDelimiter(DEFAULT_VALUE_SPLIT);
        return sub.replace(message);
    }
}
